import { createStore } from 'redux';
import { Action } from 'redux-actions';
import reducers from './reducers';

const loadState = () => {
  const serializedState = localStorage.getItem('state');
  if (serializedState === null) {
    return undefined;
  }
  return JSON.parse(serializedState);
};

const saveState = (state: QA.ReduxState) => {
  const serializedState = JSON.stringify(state);
  localStorage.setItem('state', serializedState);
};

const persistState = loadState();

const store = createStore<
  QA.ReduxState,
  Action<any>,
  any,
  any
>(reducers, persistState);

// 监听store的变化
store.subscribe(() => {
  saveState(store.getState());
});

export default store;
